package com.lxs.legou.order.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: Mcb
 * @Date: 2022/1/16 22:16
 * @Description: token工具类
 */
@Component
public class TokenDecode {

    private static final String PUBLIC_KEY = "publickey.txt";

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 获取当前请求的token
     *
     * @return
     */
    public String getToken(){
        OAuth2AuthenticationDetails autentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        return autentication.getTokenValue();
    }

    /**
     * 获取公钥
     * @return
     */
    public String getPublicKey(){
        Resource resource = new ClassPathResource(PUBLIC_KEY);

        try {
            InputStreamReader isr = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            return br.lines().collect(Collectors.joining("\n"));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取当前登录用户信息
     * @return
     * @throws JsonProcessingException
     */
    public Map<String, String> getUserInfo() throws JsonProcessingException {

        String token = getToken();

        String publicKey = getPublicKey();

        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(publicKey));
        String claims = jwt.getClaims();
        Map map = objectMapper.readValue(claims, Map.class);
        return map;
    }
}
